package com.mh.common.utils;

import com.mh.common.constant.HttpStatus;
import com.mh.common.core.exception.CustomException;
import com.mh.system.domain.LoginUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

//用户信息相关操作工具类
public class SecurityUtils {

    //获取用户名
    public static String getUsername(){
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new CustomException(HttpStatus.UNAUTHORIZED,"获取用户名异常");
        }
    }

    //获取完整用户信息
    public static LoginUserDetails getLoginUser(){
        try {
            return (LoginUserDetails)getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new CustomException(HttpStatus.UNAUTHORIZED,"获取用户信息异常");
        }
    }


    //获取Authentication(自定义的TokenAuthFilter中存储)
    public static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
